package 优先算法.前缀和.矩阵区域和;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/matrix-block-sum/description/
 */
public class Main {
    public static void main(String[] args) {
        Solution so = new Solution();
        int[][] arr = {{67,64,78},{99,98,38},{82,46,46},{6,52,55},{55,99,45}};
        int[][] rel =  so.matrixBlockSum(arr,3);
        System.out.println(Arrays.deepToString(rel));
    }
}
class Solution {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length,n = mat[0].length;//注意！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
        //创建dp数组
        long[][] dp = new long[m+1][n+1];
        for(int i = 1; i <= m; i++){
            for(int j = 1;j <= n;j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1] +mat[i-1][j-1] - dp[i-1][j-1];
            }
        }
        //2.使用

        System.out.println(Arrays.deepToString(dp));
        int[][] rel = new int[m][n];
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                //定义x1,y1\x2,y2当值越界 映射到dp右下各自评议1
                int x1 = Math.max(0,i-k)+1,y1 = Math.max(0,j-k)+1;
                int x2 = Math.min(m-1,i+k)+1,y2 = Math.min(n-1,j+k)+1;
                rel[i][j] = (int) (dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1-1][y1-1]);
            }
        }
        return rel;
    }
}